package tree;

import java.util.ArrayList;
import java.util.List;

public class AllElementsInTwoBinarySearchTrees1305 {

    public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
        List<Integer> list1 = new ArrayList<>();
        inorder(root1, list1);
        List<Integer> list2 = new ArrayList<>();
        inorder(root2, list2);
        return merge(list1,list2);
    }


    private List<Integer> merge(List<Integer> l1, List<Integer> l2) {
        List<Integer> result = new ArrayList<>();
        int index1 = 0;
        int index2 = 0;

        while (index1 != l1.size() && index2 != l2.size()) {
            if (l1.get(index1) > l2.get(index2)) {
                result.add(l2.get(index2));
                index2++;
            } else {
                result.add(l1.get(index1));
                index1++;
            }
        }
        if (index1 == l1.size()) {
            for (int i = index2; i < l2.size(); i++) {
                result.add(l2.get(i));
            }
        }
        if (index2 == l2.size()) {
            for (int i = index1; i < l1.size(); i++) {
                result.add(l1.get(i));
            }
        }
        return result;
    }

    private void inorder(TreeNode root, List<Integer> result) {
        if (root == null) {
            return;
        }
        inorder(root.left, result);
        result.add(root.val);
        inorder(root.right, result);
    }

}
